using System.Text.Json.Serialization;
using MultiAgentsClient.Service.WorkflowEngine.BaseNodes;
using MultiAgentsShared;

namespace MultiAgentsClient.Service.WorkflowEngine.BuiltInNodes;


[NodeGraphPortDef(1, 1)]
[JsonConverter(typeof(ListVariableConverter<string>))]
public class ForEachNode : BaseNode
{
    [NodeGraphParam] public ListVariable<string> sourceList;
    [NodeGraphOutput] public string foreachListElement;

    private List<string> sourceListRuntime => InsertVariable(sourceList).listOfStr;
    private int iterationIndex = 0;

    public override void Dispose()
    {
        throw new NotImplementedException();
    }

    public override async Task<NodeOutcome> ExecuteNodeAsync()
    {
        if (iterationIndex >= sourceListRuntime.Count)
        {
            //end of execution from foreach node, reset and return -1;
            iterationIndex = 0;
            var endOfExec = new NodeOutcome(NodeOutcomeStatus.Success, -1);
            return await Task.FromResult(endOfExec);
        }

        foreachListElement = sourceListRuntime[iterationIndex];
        Debug.LogLine(foreachListElement);
        runtimeContext.SetVar(Id, () => foreachListElement);

        iterationIndex++;

        var execInProgress = new NodeOutcome(NodeOutcomeStatus.Success, 0);
        return await Task.FromResult(execInProgress);
    }
}
